#! /usr/bin/python
# -*- coding:utf-8 -*-

## ========================================================================
## Copyright (C) 2007-201"  Jean-Philippe GOLAY
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
## ========================================================================

from persistance import *

class Session:
  
  def __init__(self):
    self.mDB=ManageDB(Glob.dbName, Glob.user, Glob.passwd, Glob.host)
    logging.basicConfig(filename=Glob.LOG_FILENAME,level=logging.DEBUG)


  def new(self, ip):
    u_ip = unicode(ip.replace('"', '\\"').replace("'", "\\'"), 'utf8')
    if (self.mDB.executSQL(Glob.insert_session % u_ip) == 0):
      sql=Glob.insert_session % u_ip
      logging.debug(u'Session: new() SQL error : %s' % sql)
      return 0
    else:
      if (self.mDB.executSQL(Glob.last_insert_id_session ) == 0):
        logging.debug(u'Session: new() SQL error : %s' % Glob.last_insert_id_session)
        return 0
      else:
        result=self.mDB.resultSQL()
        for row in result:
          id=row[0]
        
        d = self.check(id)
        c = u"ASZ%sCX%s" % (d[1], id)
        return c


  def check(self, id):
    if (self.mDB.executSQL(Glob.select_all_from_session_where_id % id ) == 0):
      sql=Glob.select_all_from_session_where_id % id 
      logging.debug(u'Session: check() SQL error : %s' % sql)
      return 0
    else:
      result=self.mDB.resultSQL()
      if len(result) == 0:
        return 0
      else:
        for row in result:
          ses_ip = row[1]
          ses_date = row[2]
          ses_user_id = row[3]
        return (ses_ip, ses_date, ses_user_id)
      

  def setUser(self, user_id, id):
    if (self.mDB.executSQL(Glob.update_session_where_id % (user_id, id) ) == 0):
      sql=Glob.update_session_where_id % (user_id, id)
      logging.debug(u'Session: setUser() SQL error : %s' % sql)
      return 0
    else:
      return 1    


  def delete(self, id):
    if (self.mDB.executSQL(Glob.delete_session_where_id % id) == 0):
      sql=Glob.delete_session_where_id % id
      logging.debug(u'Session: delete() SQL error : %s' % sql)
      return 0
    else:
      return 1

